package com.byit.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.byit.builder.MapBuilder;
import com.byit.constant.DefaultValue;
import com.byit.domain.AppCharacteristic;
import com.byit.domain.vo.DictVo;
import com.byit.enums.PromptInfo;
import com.byit.log.ChannelType;
import com.byit.log.Log;
import com.byit.log.OperatorType;
import com.byit.msg.MessageResult;
import com.byit.service.IAppCharacteristicService;
import com.byit.service.ISysDictService;
import com.byit.shrio.session.SessionHelper;
import com.byit.utils.MinioUtil;
import com.byit.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 特色江油 前端控制器
 *
 * @author tjm
 * @date 2019年1月9日
 */
@RestController
@RequestMapping("/api/sys/characteristic")
public class AppCharacteristicController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IAppCharacteristicService appCharacteristicService;

    @Autowired
    private ISysDictService sysDictService;

    @Autowired
    private MinioUtil minioUtil;

    /**
     * 添加 X_O_X O表示可以多个
     */
    @Log(title = "内容-链接", operate = OperatorType.DATA_INSERT, channel = ChannelType.WEB_INTER)
    @PostMapping("/add")
    public Object add(HttpSession session,
                      @RequestParam("content") String content,
                      @RequestParam("url") String url,
                      @RequestParam("type") String type,
                      Integer byOrder) {
        try {
            Long userId = SessionHelper.getUserId(session);
            String check = typeCheck(type, null);
            if (StringUtil.isNotEmpty(check)) {
                return MessageResult.error(check);
            }
            AppCharacteristic appCharacteristic = new AppCharacteristic();
            appCharacteristic.setContent(content);
            appCharacteristic.setType(type);
            appCharacteristic.setUrl(url);
            appCharacteristic.setByOrder(byOrder);
            appCharacteristic.setCreateTime(new Date());
            appCharacteristic.setUpdateTime(new Date());
            appCharacteristic.setOperationId(userId);
            appCharacteristicService.insert(appCharacteristic);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return MessageResult.error(e);
        }
    }

    /**
     * 修改
     */
    @Log(title = "内容-链接", operate = OperatorType.DATA_UPDATE, channel = ChannelType.WEB_INTER)
    @PostMapping("/update")
    public Object update(HttpSession session,
                         @RequestParam("id") Long id,
                         String content,
                         String url,
                         String type,
                         Integer byOrder) {
        try {
            Long userId = SessionHelper.getUserId(session);
            AppCharacteristic appCharacteristic = new AppCharacteristic();
            if (StringUtil.isNotEmpty(content)) {
                appCharacteristic.setContent(content);
            }
            if (StringUtil.isNotNull(type)) {
                String check = typeCheck(type, id);
                if (StringUtil.isNotEmpty(check)) {
                    return MessageResult.error(check);
                }
                appCharacteristic.setType(type);
            }
            if (StringUtil.isNotEmpty(url)) {
                appCharacteristic.setUrl(url);
            }
            if (StringUtil.isNotNull(byOrder)) {
                appCharacteristic.setByOrder(byOrder);
            }
            appCharacteristic.setId(id);
            appCharacteristic.setUpdateTime(new Date());
            appCharacteristic.setOperationId(userId);
            appCharacteristicService.updateById(appCharacteristic);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return MessageResult.error(e);
        }
    }

    /**
     * 类型判断
     *
     * @param type
     * @return
     */
    private String typeCheck(String type, Long id) {
        String res = "";
        if (type.contains("_O_")) {
            boolean flg = false;
            List<AppCharacteristic> appCharacteristics = appCharacteristicService.selectByMap(MapBuilder.newMap(2).setParam("type", type).setParam("is_del", 0).ok());
            if (appCharacteristics.size() > 1) {
                flg = true;
            } else if (appCharacteristics.size() == 1) {
                if (id == null) {
                    flg = true;
                } else {
                    if (!Objects.equals(appCharacteristics.get(0).getId(), id)) {
                        flg = true;
                    }
                }
            }
            if (flg) {
                List<DictVo> tsType = sysDictService.selectDictByType("tsType");
                for (DictVo d : tsType) {
                    if (java.util.Objects.equals(type, d.getValue())) {
                        res = d.getLabel() + "类型数据只允许存在一条";
                        break;
                    }
                }
            }
        }
        return res;
    }

    /**
     * 详情
     */
    @Log(title = "内容-链接", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    @PostMapping("/details")
    public Object details(@RequestParam("id") Long id) {
        AppCharacteristic appCharacteristic = appCharacteristicService.selectById(id);
        if (appCharacteristic.getIsDel() == 1) {
            return MessageResult.error("该数据已删除");
        }
        return MessageResult.success(appCharacteristic);
    }

    /**
     * 分页列表查询
     */
    @Log(title = "内容-链接", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    @GetMapping("/list")
    public Object list(String type,
                       @RequestParam(value = "page", defaultValue = DefaultValue.PAGE_FIRST) int page,
                       @RequestParam(value = "limit", defaultValue = DefaultValue.PAGE_SIZE) int limit) {
        Page<AppCharacteristic> pageInfo = new Page<>(page, limit);
        EntityWrapper<AppCharacteristic> wrapper = new EntityWrapper<>();
        wrapper.setSqlSelect("id,content,type,url,by_order as byOrder,count_num as countNum,create_time as createTime");
        wrapper.eq("is_del", 0);
        if (StringUtil.isNotEmpty(type)) {
            wrapper.eq("type", type);
        }
        wrapper.orderBy("by_order", true);
        wrapper.orderBy("update_time", false);
        wrapper.orderBy("create_time", false);
        Page<AppCharacteristic> list = appCharacteristicService.selectPage(pageInfo, wrapper);
        return MessageResult.warpper(PromptInfo.SYS_SECCUSS, list);
    }

    /**
     * 逻辑删除
     */
    @Log(title = "内容-链接", operate = OperatorType.DATA_DELETE, channel = ChannelType.WEB_INTER)
    @PostMapping("/del")
    public Object delete(HttpSession session, @RequestParam("ids") String ids) {
        Long userId = SessionHelper.getUserId(session);
        List<Long> idList = StringUtil.splitLong(ids, ",");
        for (Long id : idList) {
            AppCharacteristic appCharacteristic = new AppCharacteristic();
            appCharacteristic.setId(id);
            appCharacteristic.setIsDel(1);
            appCharacteristic.setOperationId(userId);
            appCharacteristic.setUpdateTime(new Date());
            appCharacteristicService.updateById(appCharacteristic);
        }
        return MessageResult.success();
    }

    /**
     * 上传图片
     */
    @Log(title = "内容-链接", operate = OperatorType.IMG_UPLOAD, channel = ChannelType.WEB_INTER)
    @PostMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile file) {
        try {
            if (null == file) {
                return MessageResult.error("文件不能为空");
            } else {
                JSONObject flg = minioUtil.uploadFile(file.getInputStream(),
                        file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")), "characteristic/");
                if ("1".equals(flg.getString("flag"))) {
                    return MessageResult.error("上传失败");
                } else {
                    return MessageResult.success(flg.getString("path"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return MessageResult.error(e);
        }
    }

    /**
     * 获取码表数据
     */
    @Log(title = "内容-链接", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    @GetMapping("/getCode")
    public Object getCode() {
        List<DictVo> tsType = sysDictService.selectDictByType("tsType");
        return MessageResult.success(tsType);
    }
}
